package com.design.classroommanagement.teacher;

import com.alibaba.android.arouter.facade.annotation.Route
import com.design.classroommanagement.Pages
import com.design.classroommanagement.api.Bookmark
import com.design.classroommanagement.api.dao.BookmarkDao
import com.design.classroommanagement.databinding.ActivityTeacherUpdateBinding
import com.laughing.lib.base.BaseFragmentNoVM
import com.laughing.lib.utils.clickWithTrigger
import com.laughing.lib.utils.runInBg
import com.laughing.lib.utils.runInMain
import com.laughing.lib.utils.saveGet
import kotlinx.android.synthetic.main.activity_teacher_update.*
import kotlinx.android.synthetic.main.fragment_add_course.classroomEt
import kotlinx.android.synthetic.main.fragment_add_course.nameEt
import kotlinx.android.synthetic.main.fragment_add_course.teacherEt

@Route(path = Pages.TeacherUpdateFragment)
open class TeacherUpdateFragment : BaseFragmentNoVM<ActivityTeacherUpdateBinding>() {
    private var bookmark: Bookmark? = null

    override fun initCompleted() {
        super.initCompleted()
        binding.apply {
            submitBtn.clickWithTrigger {
                submit()
            }
            searchBtn.clickWithTrigger {
                search()
            }
        }
    }

    fun search() {
        val key = nameEt.text.trim().toString()
        runInBg {
            var result = BookmarkDao.search(key)
            bookmark = result.saveGet(0)
            runInMain { render() }
        }
    }

    fun render() {
        binding.apply {
            nameEt.setText(bookmark?.name)
            teacherEt.setText(bookmark?.tid)
            classroomEt.setText(bookmark?.classname)
            dateEt.setText(bookmark?.date)
        }
    }

    fun submit() {
        val bookmark = bookmark?.apply {
            name = nameEt.text.toString()
            tid = teacherEt.text.toString()
            classname = classroomEt.text.toString()
            date = dateEt.text.toString()
        } ?: return

        runInBg {
            BookmarkDao.update(bookmark)
            finish()
        }
    }
}